<?php

namespace App\Module;

use App\depository\PermissionsDep;
use App\depository\RoleHasPermissionsDep;
use App\depository\RolesDep;
use App\depository\TeamDictDep;
use App\depository\TeamsDep;
use App\depository\UserHasTeamsDep;
use App\Enum\CommonEnum;
use App\Enum\PermissionsEnum;
use App\Enum\RolesEnum;
use App\Enum\TeamsEnum;
use App\Service\DictService;
use App\depository\UserDep;
use function Symfony\Component\String\s;

class TeamsModule extends BaseModule
{
    public function init($request)
    {

        $param = $request->input();

        $dictService = new DictService();
        $dictService->setUsers()->setTeamStatus()->setDictPermission();

        $data = [
            'dict' => $dictService->getDict(),
        ];

        return self::response($data);
    }


    public function add($request)
    {
        $param = $request->input();

        if (empty($param['name'])) {
            return self::response([], '请输入工会名称', 100);
        }

        $dep = new TeamsDep();
        $data = [
            'name' => $param['name'],
            'status' => $param['status'],
            'leader_id' => !empty($param['leader_id']) ? $param['leader_id'] : -1,
            'expire_at' => $param['expire_at'],
            'uuid' => create_secret()
        ];

        $teamId = $dep->add($data);

        $dictDep = new TeamDictDep();
        foreach ($param['dict'] as $dict) {
            if (empty($dict['label'])) {
                continue;
            }
            $data = [
                'team_id' => $teamId,
                'label' => $dict['label'],
                'value' => $dict['val'] ?? "",
                'permission' => $dict['permission'] ?? TeamsEnum::DICT_PERMISSION_NO
            ];
            $dictDep->add($data);
        }

        return self::response();
    }

    public function del($request)
    {
        $param = $request->input();

        $dep = new TeamsDep();

        $dep->del($param['id']);
        return self::response();
    }

    public function edit($request)
    {
        $param = $request->input();

        if (empty($param['name'])) {
            return self::response([], '请输入工会名称', 100);
        }

        $dep = new TeamsDep();
        $data = [
            'name' => $param['name'],
            'status' => $param['status'],
            'leader_id' => !empty($param['leader_id']) ? $param['leader_id'] : -1,
            'expire_at' => $param['expire_at']
        ];

        $dep->upd($param['id'], $data);

        $dictDep = new TeamDictDep();
        $dictDep->delByTeamId($param['id']);
        foreach ($param['dict'] as $dict) {
            if (empty($dict['label'])) {
                continue;
            }
            $data = [
                'team_id' => $param['id'],
                'label' => $dict['label'],
                'value' => $dict['val'] ?? "",
                'permission' => $dict['permission'] ?? TeamsEnum::DICT_PERMISSION_NO
            ];
            $dictDep->add($data);
        }


        return self::response();

    }

    public function list($request)
    {
        $param = $request->input();

        $dep = new TeamsDep();
        $userDep = new UserDep();
        $teamDictDep = new TeamDictDep();

        $resList = $dep->list($param);

        $data['list'] = $resList->map(function ($item) use ($userDep, $teamDictDep) {
            $resUser = $userDep->firstById($item->leader_id);
            $resDict = $teamDictDep->getByTeamId($item->id);
            $dict = $resDict->map(function ($item) {
                return [
                    'label' => $item->label,
                    'val' => $item->value,
                    'permission' => intval($item->permission)
                ];
            });

            return [
                'id' => $item->id,
                'name' => $item->name,
                'uuid' => $item->uuid,
                'expire_at_show' => $item->expire_at === CommonEnum::DEFAULT_TIMESTAMP ? CommonEnum::DEFAULT_NULL : $item->expire_at,
                'expire_at' => $item->expire_at,
                'leader_id' => $item->leader_id,
                'leader_show' => $resUser ? $resUser->name : CommonEnum::DEFAULT_NULL,
                'status' => $item->status,
                'status_show' => TeamsEnum::$statusArr[$item->status] ?? CommonEnum::DEFAULT_NULL,
                'created_at' => $item->created_at->toDateTimeString(),
                'dict' => count($dict) == 0 ? [['label' => '', 'val' => '', 'permission' => TeamsEnum::DICT_PERMISSION_NO]] : $dict
            ];
        });

        $data['page'] = [
            'per_page' => $param['per_page'],
            'current_page' => $param['current_page'],
            'total_page' => $resList->lastPage(),
            'total' => $resList->total(),
        ];

        return self::response($data);
    }


    public function subDetail($request)
    {

        $param = $request->input();

        $userId = $request->user()->id;
        $teamId = $request->headers->get('TeamId');

        $userHasTeamsDep = new UserHasTeamsDep();
        $resUserHasTeams = $userHasTeamsDep->firstByTeamIdUserId($teamId, $userId);

        $teamsDep = new TeamsDep();
        $dictDep = new TeamDictDep();
        $resTeam = $teamsDep->first($teamId);
        $resDict = $dictDep->getByTeamId($teamId);

        if (!$resUserHasTeams) {
            $tmp = $resDict->filter(function($item){
                return in_array($item->permission,[TeamsEnum::DICT_PERMISSION_SEE,TeamsEnum::DICT_PERMISSION_EDIT]);
            });
        }else{
            $tmp = $resDict;
        }

        $dict = $tmp->map(function ($item) {
            return [
                'id' => $item['id'],
                'label' => $item->label,
                'val' => $item->value,
                'permission' => $item->permission
            ];
        });

        $data['dict'] = $dict;

        $data['server'] = [
            'version' => $resTeam->version ? $resTeam->version : CommonEnum::DEFAULT_NULL,
            'is_update' => $resTeam->is_update,
            'update_desc' => $resTeam->update_desc ? $resTeam->update_desc : CommonEnum::DEFAULT_NULL,
            'is_open' => $resTeam->is_open,
            'open_desc' => $resTeam->open_desc ? $resTeam->open_desc : CommonEnum::DEFAULT_NULL,
            'reason' => $resTeam->reason,
            'permission_group' => $resTeam->permission_group,
            'secret_group' => $resTeam->secret_group
        ];

        return self::response($data);
    }

    public function detailInit($request){

        $dictService = new DictService();

        $dictService->setTextButton()->setDictPermission();

        $data['dict'] = $dictService->getDict();
        return self::response($data);
    }

    public function subEditServer($request)
    {

        $param = $request->input();
        $teamId = $request->headers->get('TeamId');

        $data = [
//            'is_open' => $param['is_open'],
            'reason' => $param['reason'] ?? "",
            'permission_group' => $param['permission_group'] ?? "",
            'secret_group' => $param['secret_group'] ?? ""
        ];

        $teamDep = new TeamsDep();
        $teamDep->upd($teamId, $data);

        return self::response();
    }

    public function subEditDict($request)
    {

        $param = $request->input();

        $dictDep = new TeamDictDep();

        foreach ($param as $item) {
            $data = [
                'label' => $item['label'],
                'value' => $item['val']
            ];
            $dictDep->upd($item['id'], $data);
        }
        return self::response();
    }


    public function enumToDict($enum) {
        $res = [];
        foreach ($enum as $index => $item) {
            $res[] = [
                'label' => $item,
                'value' => $index,
            ];
        }
        return $res;
    }

    public function subUpdateServer($request){

        $param = $request->input();
        $teamId = $request->headers->get('TeamId');

        $data = [
            'is_update' => 1,
        ];

        $teamDep = new TeamsDep();
        $teamDep->upd($teamId, $data);

        return self::response();
    }

    public function subOpen($request){
        $param = $request->input();
        $teamId = $request->headers->get('TeamId');

        $teamDep = new TeamsDep();
        $resTeam = $teamDep->first($teamId);
        if($resTeam->expire_at <= date('Y-m-d H:i:s')){
            return self::response([],'工会过期',200);
        }

        $data = [
            'is_open' => $param['is_open'],
        ];

        $teamDep = new TeamsDep();
        $teamDep->upd($teamId, $data);

        return self::response();
    }
}

